<?php

class Service {
	private $AWSAccessKeyId = "AKIAI25QJIHO2ZNPUOXA";
	private $SecretAccessKey = "Tn2wJuYclh0x31PLCKv7PhE7mgsCbQuU0hGW/JL1"; 
	
	public function callService($service) {
		$string = $service;
		$string = str_replace("\n", "", $string);
		
		$prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
		$prependString = $prepend . $string;
	
		$signature = base64_encode(hash_hmac("sha256", $prependString, $this->SecretAccessKey, True));
		$signature = str_replace("+", "%2B", $signature);
		$signature = str_replace("=", "%3D", $signature);
		$baseUrl = "http://webservices.amazon.com/onca/xml?";
		$signedRequest = $baseUrl . $string . "&Signature=" . $signature;
	
		$c = curl_init(); 
	    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
	    curl_setopt($c, CURLOPT_URL, $signedRequest); 
	    $response = curl_exec($c); 
	    curl_close($c);
		$xml = simplexml_load_string($response);
		return $xml->Items;
	}

	public function lookup($itemId, $type=1){
		if ($type == 1)	{
			$timestamp = gmdate("Y-m-d\TH:i:s\Z");
			$timestamp = str_replace(":", "%3A", $timestamp);
			$responseGroup = "ItemAttributes,Offers,Images,RelatedItems,Similarities";
			$responseGroup = str_replace(",", "%2C", $responseGroup);
			$relationshipType = "AuthorityTitle";
			return $this->callService("AWSAccessKeyId=$this->AWSAccessKeyId&ItemId=$itemId&Operation=ItemLookup&RelationshipType=$relationshipType&ResponseGroup=$responseGroup&Service=AWSECommerceService&Timestamp=$timestamp&Version=2009-01-06")->Item;
		} else if ($type == 2) {
			$apiKey = "9u8z82apejvpufvfdm6xgh3s";
			$url = "http://api.remix.bestbuy.com/v1/products(productId=$itemId)?apiKey=$apiKey";
			$c = curl_init(); 
		    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
		    curl_setopt($c, CURLOPT_URL, $url); 
		    $response = curl_exec($c); 
		    curl_close($c);
			$xml = simplexml_load_string($response);
			return $xml;
		}
	}
	
	public function search($keyword) {
		$timestamp = gmdate("Y-m-d\TH:i:s\Z");
		$timestamp = str_replace(":", "%3A", $timestamp);
		$responseGroup = "ItemAttributes,Images";
		$responseGroup = str_replace(",", "%2C", $responseGroup);
		return $this->callService("AWSAccessKeyId=$this->AWSAccessKeyId&Keywords=$keyword&Operation=ItemSearch&ResponseGroup=$responseGroup&SearchIndex=All&Service=AWSECommerceService&Timestamp=$timestamp&Version=2009-01-06");
	}
}

?>